import React, { useCallback, useEffect, useState } from 'react';
import { connect, ConnectedProps } from 'react-redux';
import { RootState } from 'src/app/rootReducer';

import { formatUrl, Params } from 'src/utils/urlUtiles';
import { Navbar, BodyContainer, Show, ClassList } from 'src/components';
import { usrSourceSelector } from 'src/redux/usr';
import { classSelector, epicActions as movieEpics, videosSelector } from 'src/redux/movie';
import { actions as otherActions, loadingSelector } from 'src/redux/other';
import { actions as wactchActions } from 'src/redux/watch';

const WebContainer: React.FC<ReduxProps> = ({
  usrSource,
  loadClassList,
  loadClassDetails,
  videos,
  classes,
  router,
  setCancelAction,
  setWatchVideo,
  loading,
  setLoading,
}) => {
  const [page, setPage] = useState(videos.attr.page);

  useEffect(() => {
    setPage(videos.attr.page);
  }, [videos.attr.page]);

  const fetchDetails = useCallback(
    (address: string) => {
      setCancelAction('homeCancel');
      loadClassDetails(address);
    },
    [loadClassDetails, setCancelAction],
  );

  useEffect(() => {
    if (router.location.pathname.includes('/home')) {
      loadClassList(usrSource.currentSource.address);
      fetchDetails(usrSource.currentSource.address + formatUrl(router.location.query || {}));
    }
  }, [fetchDetails, loadClassList, router.location.pathname, router.location.query, usrSource.currentSource.address]);

  const fetchSourceDetails = useCallback(
    (params: Partial<Params> = {}) => {
      setLoading(true);
      const paramsString = formatUrl(params);
      fetchDetails(usrSource.currentSource.address + paramsString);
    },
    [fetchDetails, setLoading, usrSource.currentSource.address],
  );

  // show componet fetch details
  const showFetchSourceDetails = useCallback(
    (page: number) => {
      setPage(page);
      fetchSourceDetails({ pg: `${page}` });
    },
    [fetchSourceDetails],
  );

  return (
    <React.Fragment>
      <Navbar />
      <BodyContainer>
        <ClassList classes={classes} query={router.location.query} />
        <Show
          loading={loading}
          videos={videos}
          fetchSourceDetails={showFetchSourceDetails}
          page={page}
          setWatchVideo={setWatchVideo}
        />
      </BodyContainer>
    </React.Fragment>
  );
};

const connector = connect(
  (state: RootState) => ({
    usrSource: usrSourceSelector(state),
    videos: videosSelector(state),
    classes: classSelector(state),
    loading: loadingSelector(state),
    router: state.router,
  }),
  {
    loadClassList: movieEpics.loadClassList,
    loadClassDetails: movieEpics.loadClassDetails,
    clearClassDetails: movieEpics.clearClassDetails,
    setCancelAction: otherActions.setCancelAction,
    setWatchVideo: wactchActions.setWatchVideo,
    setLoading: otherActions.setLoading,
  },
);

type ReduxProps = ConnectedProps<typeof connector>;
export const Home = connector(WebContainer);
